package main

import (
	"compress/gzip"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"wx-api/adx-bid/services/bid"
	"wx-api/adx-bid/services/demo"
	"wx-api/adx-bid/services/track"
)

func RouteApi(m string) *gin.Engine {
	var r *gin.Engine
	//if m == "product" {
	r = gin.New()
	//} else {
	//	gin.SetMode("debug")
	//	r = gin.Default()
	//}
	//gin.SetMode("debug")
	//r = gin.Default()
	r.Use(gin.Recovery())

	//负载探活
	r.Any("/", Rz)
	r.POST("/demo", func(context *gin.Context) {
		demo.BidDemo(context)
	})
	r.POST("/dbid", func(context *gin.Context) {
		tbid("3", context) //dsp
	})
	r.POST("/abid", func(context *gin.Context) {
		tbid("2", context) //adx
	})
	r.POST("/sbid", func(context *gin.Context) {
		tbid("1", context) //ssp
	})
	r.Any("/thck/:ty", func(context *gin.Context) {
		ty := context.Param("ty")
		p := context.Query("tc")
		tprc := context.Query("tpc")
		tprc, _ = url.QueryUnescape(tprc)
		tprc = strings.ReplaceAll(tprc, " ", "")
		if tprc == "" || tprc == "__PRICE__" {
			tprc = ""
		}
		go track.HTrack(ty, p, tprc)
		context.AbortWithStatus(200)
		return
	})
	return r
}
func tbid(sty string, context *gin.Context) {
	id := context.Query("id")
	name := context.Query("name")
	if id == "" || name == "" {
		context.AbortWithStatus(204)
		return
	}
	isdebugs := context.GetHeader("debug")
	body, cty, err := GetReqBody(context)
	if err != nil || len(body) == 0 {
		context.Status(400)
		return
	}
	isdebug := false
	if isdebugs == "true" {
		isdebug = true
	}
	data, tys, errs := bid.HBid(sty, id, name, cty, isdebug, body)
	if tys == "proto" {
		context.ProtoBuf(200, data)
		return
	}
	if errs != nil {
		context.AbortWithStatus(204)
		return
	}
	context.JSON(200, data)
	return
}
func Rz(c *gin.Context) {
	str := make(map[string]string)
	str["msg"] = "success"
	c.JSON(http.StatusOK, str)
	return
}

func GetReqBody(c *gin.Context) ([]byte, string, error) {
	tmptype := c.GetHeader("Content-Type")
	var body []byte
	var err error
	if c.Request.Header.Get("Content-Encoding") == "gzip" {
		tbody, errs := gzip.NewReader(c.Request.Body)
		if errs != nil {
			fmt.Println("http read unzip is failed,err: ", errs)
			return nil, tmptype, errs
		}
		body, err = ioutil.ReadAll(tbody)
	} else {
		body, err = ioutil.ReadAll(c.Request.Body)
	}
	if err != nil {
		fmt.Println("http rest is failed,err: ", err)
		return nil, tmptype, err
	}
	return body, tmptype, nil
}
